import json
import os
import requests
import sys

import util

url = os.getenv('JIANMU_BOOT_WEBHOOK_URL')
secret = os.getenv('JIANMU_SECRET')
signs = util.get_signature(secret)
text = os.getenv('JIANMU_MSG_TEXT')
at_mobiles = os.getenv('JIANMU_AT_MOBILES')
at_user_ids = os.getenv('JIANMU_AT_USER_IDS')
is_at_all = os.getenv('JIANMU_IS_AT_ALL')

headers = {
    'Content-Type': 'application/json'
}
params = {
    'sign': signs.get('sign'),
    'timestamp': signs.get('timestamp'),
}
try:
    atMobiles = json.loads(at_mobiles if at_mobiles else '[]')
except Exception as e:
    print('error: 参数at_mobiles格式错误，如：\'["10012"]\'')
    sys.exit(1)
try:
    atUserIds = json.loads(at_user_ids if at_user_ids else '[]')
except Exception as e:
    print('error: 参数at_user_ids格式错误，如：\'["1"]\'')
    sys.exit(1)

data = {
    'msgtype': 'text',
    'text': {
        'content': text
    },
    "at": {
        "atMobiles": atMobiles,
        "atUserIds": atUserIds,
        "isAtAll": is_at_all == 'true' if True else False
    }
}

response = requests.post(url=url, headers=headers, params=params, data=json.dumps(data))
content = response.json()
if content.get("errcode") != 0:
    raise Exception(content)
print(content)
